//
//  NineViewController.swift
//  swiftTS
//
//  Created by 航电 on 2020/4/3.
//  Copyright © 2020 航电. All rights reserved.
//

import UIKit
import WebKit

class NineViewController: UIViewController {

    fileprivate var _leftBackItem:UIBarButtonItem?;
    fileprivate var _activityIndicatorView:UIActivityIndicatorView?;
    fileprivate var _userContent:WKUserContentController!
    fileprivate var _webView:WKWebView!;
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        self.navigationController?.setNavigationBarHidden(true, animated: false);
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        self.navigationController?.setNavigationBarHidden(false, animated: false);
        
        //离开界面 移除消息
        if (_userContent != nil) {
            _userContent?.removeScriptMessageHandler(forName: "webViewApp")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.onCreateUIForNavigation();
        self.onCreateUIForView();
    }
    

    //TODO:UI
    fileprivate func onCreateUIForNavigation() {
        _leftBackItem = UIBarButtonItem(title: "返回", style: UIBarButtonItem.Style.plain, target: self, action: #selector(onBackAction));
    }
    
    fileprivate func onCreateUIForView() {
        
        //前端添加
        //window.webkit.messageHandlers.webViewApp.postMessage({get_selection_txt:rng_string});
        
        _userContent = WKUserContentController();
        //添加消息处理
        _userContent.add(self, name: "webViewApp");
        
        let configuration = WKWebViewConfiguration();
        configuration.userContentController = _userContent;
        
        _webView = WKWebView(frame: CGRect(x: 0, y: 0, width: screenMainSize.width, height: screenMainSize.height), configuration: configuration);
        _webView.uiDelegate = self;
        _webView.navigationDelegate = self;
        _webView.scrollView.isScrollEnabled = false;
        self.view.addSubview(_webView);
        
        let urlString = "http://x.pai-xiu.com:9018/#/my-details?projectId=1007&projectName=%E5%BE%85%E5%88%A0%E9%99%A4-%E8%BF%90%E8%90%A5%E9%83%A8%E9%A1%B9%E7%9B%AE&userId=346&userName=%E8%83%A1%E9%9D%92&avatar=http://www.pai-fms.com/uploadFiles/uploadImgs/d4cb9546e49243fb938624702ac18251.jpg&token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxNTIyMDEyMDQ1Ml8zNDYiLCJpYXQiOjE1ODU4OTYxODN9.6KYHj5Ups8RWXYSMyJWINrQtxfB1B7y-m4PYn772QN4";
//        let urlString = "http://www.chinadaily.com.cn";
        let request = NSMutableURLRequest(url: NSURL(string: urlString)! as URL);
        _webView.load(request as URLRequest);
        
        _activityIndicatorView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.medium);
        _activityIndicatorView?.center = self.view.center;
        _activityIndicatorView?.color = .red;
        self.view.insertSubview(_activityIndicatorView!, aboveSubview: _webView);
    }
    
    //TODO:Actions
    @objc fileprivate func onBackAction() {
        self.navigationController?.dismiss(animated: true, completion: nil);
    }

}

extension NineViewController:WKUIDelegate {
    //创建一个新的webview
//    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
//        return nil;
//    }
    
    func webViewDidClose(_ webView: WKWebView) {
        
    }
    
    //弹出警告框时调用
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        completionHandler();
    }
    
    //弹出确认框时调用
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        completionHandler(true);
    }
    
    //弹出输入框时调用
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        completionHandler("");
    }
    
    //是否需要预览
    func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool {
        return true;
    }
    
    //预览时返回一个控制器显示一个预览
    func webView(_ webView: WKWebView, previewingViewControllerForElement elementInfo: WKPreviewElementInfo, defaultActions previewActions: [WKPreviewActionItem]) -> UIViewController? {
        return nil;
    }
    
    //完成预览
    func webView(_ webView: WKWebView, commitPreviewingViewController previewingViewController: UIViewController) {
        
    }
    
//    func webView(_ webView: WKWebView, contextMenuConfigurationForElement elementInfo: WKContextMenuElementInfo, completionHandler: @escaping (UIContextMenuConfiguration?) -> Void) {
//
//    }
    
    func webView(_ webView: WKWebView, contextMenuWillPresentForElement elementInfo: WKContextMenuElementInfo) {
        
    }
    
    func webView(_ webView: WKWebView, contextMenuForElement elementInfo: WKContextMenuElementInfo, willCommitWithAnimator animator: UIContextMenuInteractionCommitAnimating) {
        
    }
    
    func webView(_ webView: WKWebView, contextMenuDidEndForElement elementInfo: WKContextMenuElementInfo) {
        
    }
}

extension NineViewController:WKNavigationDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        print("是否允许加载网页？");
        let url:String = navigationAction.request.url!.absoluteString;
        let requestUrl = NSString(string: url);
        if requestUrl.range(of: "firstclick://close").location != NSNotFound {
            decisionHandler(WKNavigationActionPolicy.cancel);
            self.onBackAction();
            return;
        }
        decisionHandler(WKNavigationActionPolicy.allow);
    }
    
//    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
//        returnqi
//    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        print("是否允许接受响应？");
        let requestUrl = navigationResponse.response.url?.absoluteString;
        decisionHandler(WKNavigationResponsePolicy.allow);
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        print("准备开始加载网页...");
        _activityIndicatorView?.startAnimating();
    }
    
//    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {
//        
//    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        print("加载失败返回！");
        _activityIndicatorView?.stopAnimating();
        if _leftBackItem != nil {
            self.navigationItem.leftBarButtonItem = _leftBackItem;
        }
    }
    
    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
        print("提交请求，加载网页");
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        print("网页加载完成！");
        _activityIndicatorView?.stopAnimating();
        
        //swift->JS 需要在加载完成后调用，需要前端提供点击方法名,例子中用到的是返回按钮点击事件
        webView.evaluateJavaScript("close()") { (item, error) in
            
        }
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        print("网页加载失败！");
        _activityIndicatorView?.stopAnimating();
        if _leftBackItem != nil {
            self.navigationItem.leftBarButtonItem = _leftBackItem;
        }
    }
    
//    func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//
//    }
    
    func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        
    }
}

extension NineViewController:WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}

